package com.movitech.wechat;

import com.gson.util.Tools;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

public class WeChatServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;
  private final Logger LOGGER = Logger.getLogger(WeChatServlet.class);

  public void destroy()
  {
    this.LOGGER.info("WeChatFilter已经销毁");
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    String outPut = "error";
    String _token = "WECHAT1234567890";
    String signature = request.getParameter("signature");
    String timestamp = request.getParameter("timestamp");
    String nonce = request.getParameter("nonce");
    String echostr = request.getParameter("echostr");

    if (WeChat.checkSignature(_token, signature, timestamp, nonce).booleanValue()) {
      outPut = echostr;
    }
    response.getWriter().write(outPut);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/xml");
    ServletInputStream in = request.getInputStream();
    String xmlMsg = Tools.inputStream2String(in);
    this.LOGGER.debug("输入消息:[" + xmlMsg + "]");
    String xml = WeChat.processing(xmlMsg);
    this.LOGGER.debug("xml数据:[" + xml + "]");
    response.getWriter().write(xml);
  }
}